package com.zzyl.serve.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class WechatUtil {
    private static final String OPENID_URL="https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    public  String getOpenid(String code){
        //准备请求参数
        Map<String,Object> params = new HashMap<>();
        params.put("appid",appid);
        params.put("secret",secret);
        params.put("js_code",code);
        params.put("grant_type","authorization_code");


        String result = HttpUtil.get(OPENID_URL,params);

        //解析结果
        JSONObject jsonResult = JSONUtil.parseObj(result);
        if(Objects.nonNull(jsonResult.getInt("errcode"))){
            throw new BaseException(jsonResult.getStr("errmsg"));
        }
        return jsonResult.getStr("openid");
    }

    public String getPhone(String phoneCode){
        //准备请求参数
        Map<String,Object> params = new HashMap<>();
        params.put("code",phoneCode);

        //向微信平台发送api请求
        String result = HttpUtil.post(PHONE_URL + getToken(),JSONUtil.toJsonStr(params));


        //解析结果
        JSONObject jsonResult = JSONUtil.parseObj(result);
        if (jsonResult.getInt("errcode") != 0) {
        throw new BaseException(jsonResult.getStr("errmsg"));
        }
        return jsonResult.getJSONObject("phone_info").getStr("phoneNumber");
        }
        public String getToken(){
        //准备参数
            Map<String,Object> params = new HashMap<>();
            params.put("grant_type","client_credential");
            params.put("appid",appid);
            params.put("secret",secret);

            //向微信平台发请求，获取微信平台的token
            String result = HttpUtil.get(TOKEN_URL,params);

            //解析结果
            JSONObject jsonResult = JSONUtil.parseObj(result);

            return jsonResult.getStr("access_token");
        }
    }

